﻿#include "CPanelDeviceList.h"

#include <QLabel>
#include <QListView>
#include <QModelIndex>
#include <QPushButton>
#include <QStandardItemModel>
#include <QVBoxLayout>

#include "global.h"

class CPanelDeviceList::CPanelDeviceListPrivate
{
public:
    ZLDeviceConfig config;
    QString prev_device_id;

    QWidget *content;
    QListView *view;
    QStandardItemModel *model;

    CPanelDeviceListPrivate(QWidget *parent) :
        prev_device_id(""),
        view(new QListView(parent)),
        model(new QStandardItemModel(parent))
    {
    }
};

CPanelDeviceList::CPanelDeviceList(QWidget *parent) :
    CPanelWidget(parent),
    p_(new CPanelDeviceListPrivate(this))
{
    // layout
    QVBoxLayout *lay1 = new QVBoxLayout;
    lay1->addWidget(p_->view);
    lay1->setMargin(0);
    lay1->setSpacing(0);
    getContent()->setLayout(lay1);
    getHeaderButton(0)->hide();
    getHeaderButton(1)->hide();
    setWindowTitle(tr("Device List"));

    // properties
    p_->view->setModel(p_->model);
    p_->view->setEditTriggers(QAbstractItemView::NoEditTriggers);
    p_->view->setSelectionMode(QAbstractItemView::SingleSelection);
    p_->view->setSelectionBehavior(QAbstractItemView::SelectRows);
    p_->view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    connect(p_->view, &QListView::clicked, this, &CPanelDeviceList::event_tree_item_clicked);
}

CPanelDeviceList::~CPanelDeviceList()
{
}

void CPanelDeviceList::setDeviceConfig(const ZLDeviceConfig &config)
{
    p_->config = config;
    p_->prev_device_id = "";
    p_->model->clear();

    // append zlbase device
    for (const auto &d : config.zlbase_info.devices)
    {
        QList<QStandardItem *> row;
        QStandardItem *item_id = new QStandardItem(QString("%1 @ %2").arg(d.name.c_str()).arg(d.number));
        item_id->setData(d.id.c_str(), Qt::UserRole);

        // todo add status column

        row.append(item_id);
        p_->model->appendRow(row);
    }

    // todo append peri device
}

void CPanelDeviceList::event_tree_item_clicked(const QModelIndex &index)
{
    auto index_id = p_->model->index(index.row(), 0);
    auto id = p_->model->data(index_id, Qt::UserRole).toString();
    if (id.isEmpty() || id.isNull() || p_->prev_device_id == id)
    {
        return;
    }

    p_->prev_device_id = id;
    emit deviceChanged(id);
}
